#include "Precomp.h"
#include "ResourceManager.h"
#include <algorithm>
#include "Map.h"
#include "Utils.h"
#include <PhysFS++.h>
#include <iostream>

static void* buffer=0;
static size_t size=1024;

struct initializer
{
	initializer()
	{
		buffer=malloc(size);
	}
	~initializer()
	{
		free(buffer);
	}

}_initializer;

void adjustBuffer(size_t newSize)
{
	if(newSize>size)
		buffer=realloc(buffer,newSize);
}

sf::Image& ResourceManager::loadImage(const wstring& path)
{
	std::map<wstring,sf::Image>::iterator i=images.find(path);
	if(i==images.end())
	{
		images[path]=sf::Image();
		i=images.find(path);
		PhysFS::ifstream file(toUTF8(path.c_str()).c_str());
		adjustBuffer(file->size());
		file.read((char*)buffer,file->size());
		i->second.LoadFromMemory((const char*)buffer,file->size());
	}
	return i->second;
}

Map* ResourceManager::loadMap(const SQChar* path)
{
	std::map<std::wstring,Map*>::iterator i=maps.find(path);
	if(i==maps.end())
	{
		Map* map=new Map();
		if(!map->loadFromFile(path))
		{
			delete map;
			map=NULL;
		}			
		maps[path]=map;
		i=maps.find(path);
	}
	return i->second;
}

Map* ResourceManager::newMap(const SQChar* path)
{
	Map* map=new Map();
	maps[path]=map;
	map->saveToFile(path);
	return map;
}

void ResourceManager::unloadMap(const SQChar* path)
{
	std::map<std::wstring,Map*>::iterator i=maps.find(path);
	if(i!=maps.end())
	{
		delete (*i).second;
		maps.erase(i);
	}
}

void deleteMap(std::pair<std::wstring,Map*> pair)
{
	delete pair.second;
}

ResourceManager::~ResourceManager()
{
	for_each(maps.begin(),maps.end(),deleteMap);
}